package com.css.zfzx.sjcj.modules.hddcGeophySvyFaultPoint.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.constants.PlatformConstants;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.PlatformDateUtils;
import com.css.bpm.platform.utils.PlatformObjectUtils;
import com.css.bpm.platform.utils.PlatformPageUtils;
import com.css.bpm.platform.utils.PlatformSessionUtils;
import com.css.bpm.platform.utils.UUIDGenerator;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.hddcGeophySvyFaultPoint.repository.HddcGeophysvyfaultpointNativeRepository;
import com.css.zfzx.sjcj.modules.hddcGeophySvyFaultPoint.repository.HddcGeophysvyfaultpointRepository;
import com.css.zfzx.sjcj.modules.hddcGeophySvyFaultPoint.repository.entity.HddcGeophysvyfaultpointEntity;
import com.css.zfzx.sjcj.modules.hddcGeophySvyFaultPoint.service.HddcGeophysvyfaultpointService;
import com.css.zfzx.sjcj.modules.hddcGeophySvyFaultPoint.viewobjects.HddcGeophysvyfaultpointPageVO;
import com.css.zfzx.sjcj.modules.hddcGeophySvyFaultPoint.viewobjects.HddcGeophysvyfaultpointQueryParams;
import com.css.zfzx.sjcj.modules.hddcGeophySvyFaultPoint.viewobjects.HddcGeophysvyfaultpointVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 地球物理探测数据-地球物理探测断点-点管理
 * @author zhangcong
 * @date 2020-11-30
 */
@Service
public class HddcGeophysvyfaultpointServiceImpl implements HddcGeophysvyfaultpointService {

    private final HddcGeophysvyfaultpointRepository hddcGeophysvyfaultpointRepository;
    private final HddcGeophysvyfaultpointNativeRepository hddcGeophysvyfaultpointNativeRepository;
    private final GeophysicsExploreBreakPointExcelVerifyHandler geophysicsExploreBreakPointExcelVerifyHandler;

    @Autowired
    public HddcGeophysvyfaultpointServiceImpl(HddcGeophysvyfaultpointRepository hddcGeophysvyfaultpointRepository,
                                              HddcGeophysvyfaultpointNativeRepository hddcGeophysvyfaultpointNativeRepository,
                                              GeophysicsExploreBreakPointExcelVerifyHandler geophysicsExploreBreakPointExcelVerifyHandler) {
        this.hddcGeophysvyfaultpointRepository = hddcGeophysvyfaultpointRepository;
        this.hddcGeophysvyfaultpointNativeRepository = hddcGeophysvyfaultpointNativeRepository;
        this.geophysicsExploreBreakPointExcelVerifyHandler = geophysicsExploreBreakPointExcelVerifyHandler;
    }

    @Override
    public JSONObject queryHddcGeophysvyfaultpoints(HddcGeophysvyfaultpointQueryParams queryParams, int curPage, int pageSize,String sort,String order) {
        Page<HddcGeophysvyfaultpointPageVO> hddcGeophysvyfaultpointPage = this.hddcGeophysvyfaultpointNativeRepository.queryHddcGeophysvyfaultpoints(queryParams, curPage, pageSize, sort, order);
        return PlatformPageUtils.formatPageData(hddcGeophysvyfaultpointPage);
    }


    @Override
    public HddcGeophysvyfaultpointEntity getHddcGeophysvyfaultpoint(String id) {
        return this.hddcGeophysvyfaultpointRepository.findById(id).orElse(null);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcGeophysvyfaultpointEntity saveHddcGeophysvyfaultpoint(HddcGeophysvyfaultpointEntity hddcGeophysvyfaultpoint) {
        String uuid = UUIDGenerator.getUUID();
        hddcGeophysvyfaultpoint.setUuid(uuid);
        hddcGeophysvyfaultpoint.setCreateUser(PlatformSessionUtils.getUserId());
        Timestamp now = PlatformDateUtils.getCurrentTimestamp();
        hddcGeophysvyfaultpoint.setCreateTime(now);
        hddcGeophysvyfaultpoint.setUpdateTime(now);
        hddcGeophysvyfaultpoint.setIsValid(PlatformConstants.Y);
        hddcGeophysvyfaultpoint.setQualityinspectionStatus(PlatformConstants.N);
        hddcGeophysvyfaultpoint.setExtends10(PlatformConstants.Y);
        this.hddcGeophysvyfaultpointRepository.save(hddcGeophysvyfaultpoint);
        return hddcGeophysvyfaultpoint;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcGeophysvyfaultpointEntity updateHddcGeophysvyfaultpoint(HddcGeophysvyfaultpointEntity hddcGeophysvyfaultpoint) {
        HddcGeophysvyfaultpointEntity entity = hddcGeophysvyfaultpointRepository.findById(hddcGeophysvyfaultpoint.getUuid()).get();
        UpdateUtil.copyNullProperties(entity,hddcGeophysvyfaultpoint);
        hddcGeophysvyfaultpoint.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcGeophysvyfaultpoint.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcGeophysvyfaultpointRepository.save(hddcGeophysvyfaultpoint);
        return hddcGeophysvyfaultpoint;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcGeophysvyfaultpoints(List<String> ids) {
        List<HddcGeophysvyfaultpointEntity> hddcGeophysvyfaultpointList = this.hddcGeophysvyfaultpointRepository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(hddcGeophysvyfaultpointList) && hddcGeophysvyfaultpointList.size() > 0) {
            for(HddcGeophysvyfaultpointEntity hddcGeophysvyfaultpoint : hddcGeophysvyfaultpointList) {
                hddcGeophysvyfaultpoint.setIsValid(PlatformConstants.N);
                hddcGeophysvyfaultpoint.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcGeophysvyfaultpoint.setUpdateTime(new Date());
                this.hddcGeophysvyfaultpointRepository.save(hddcGeophysvyfaultpoint);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        return PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
    }

    @Override
    public void exportFile(HddcGeophysvyfaultpointQueryParams queryParams, HttpServletResponse response) {
        List<HddcGeophysvyfaultpointEntity> yhDisasterEntities = hddcGeophysvyfaultpointNativeRepository.exportYhDisasters(queryParams);
        List<HddcGeophysvyfaultpointVO> list=new ArrayList<>();
        for (HddcGeophysvyfaultpointEntity entity:yhDisasterEntities) {
            HddcGeophysvyfaultpointVO yhDisasterVO=new HddcGeophysvyfaultpointVO();
            BeanUtils.copyProperties(entity,yhDisasterVO);
            list.add(yhDisasterVO);
        }
        EasyPoiExcelUtil.exportExcel(list, "地球物理探测断点-点", "地球物理探测断点-点",
                HddcGeophysvyfaultpointVO.class, "地球物理探测断点-点.xls", response);
    }

    @Override
    public String importExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            params.setVerifyHandler(geophysicsExploreBreakPointExcelVerifyHandler);
            // 获取到Excel数据
            ExcelImportResult<HddcGeophysvyfaultpointVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcGeophysvyfaultpointVO.class, params);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                for (HddcGeophysvyfaultpointVO vo : result.getFailList()) {
                    returnMsg.append("第").append(vo.getRowNum()).append("行").append(vo.getErrorMsg()).append("<br/>");
                }
                if (returnMsg.length() > 0)
                    return returnMsg.toString();
            }
            List<HddcGeophysvyfaultpointVO> list = result.getList();
            //保存
            saveDisasterList(list);
            return returnMsg.append("成功导入").append(result.getList().size()).toString();
        } catch (Exception e) {
            return "导入失败，请检查数据正确性";
        }
    }
    /**
     * 批量存入库表并且返回错误数量
     */
    public void saveDisasterList(List<HddcGeophysvyfaultpointVO> list) {
        for (HddcGeophysvyfaultpointVO hddcGeophysvyfaultpointVO : list) {
            HddcGeophysvyfaultpointEntity yhDisasterEntity = new HddcGeophysvyfaultpointEntity();
            BeanUtils.copyProperties(hddcGeophysvyfaultpointVO, yhDisasterEntity);
            saveHddcGeophysvyfaultpoint(yhDisasterEntity);
        }
    }
    @Override
    public void deleteByProjectId(List<String> projectIds) {
        List<HddcGeophysvyfaultpointEntity> hddcGeophysvyfaultpointList = this.hddcGeophysvyfaultpointRepository.queryHddcGeophysvyfaultpointsByProjectId(projectIds);
        if(!PlatformObjectUtils.isEmpty(hddcGeophysvyfaultpointList) && hddcGeophysvyfaultpointList.size() > 0) {
            for(HddcGeophysvyfaultpointEntity hddcGeophysvyfaultpoint : hddcGeophysvyfaultpointList) {
                hddcGeophysvyfaultpoint.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcGeophysvyfaultpoint.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcGeophysvyfaultpoint.setIsValid("0");
                this.hddcGeophysvyfaultpointRepository.save(hddcGeophysvyfaultpoint);
            }
        }
    }

    @Override
    public void deleteByTaskId(List<String> taskIds) {
        List<HddcGeophysvyfaultpointEntity> hddcGeophysvyfaultpointList = this.hddcGeophysvyfaultpointRepository.queryHddcGeophysvyfaultpointsByTaskId(taskIds);
        if(!PlatformObjectUtils.isEmpty(hddcGeophysvyfaultpointList) && hddcGeophysvyfaultpointList.size() > 0) {
            for(HddcGeophysvyfaultpointEntity hddcGeophysvyfaultpoint : hddcGeophysvyfaultpointList) {
                hddcGeophysvyfaultpoint.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcGeophysvyfaultpoint.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcGeophysvyfaultpoint.setIsValid("0");
                this.hddcGeophysvyfaultpointRepository.save(hddcGeophysvyfaultpoint);
            }
        }
    }

}
